<?php

namespace app\configure\controller;

use app\configure\model\ConfigBannerModel;
use think\admin\Controller;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class Banner extends Controller
{
    /**
     * 当前操作数据库
     * @var string
     */
    private string $table = 'ConfigBanner';

    /**
     * 轮播图管理
     * @auth true
     * @menu true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        $this->title = '轮播图管理';
//        $this->type =$this->request->param('type', 'index');
        $this->_query(ConfigBannerModel::class)->like('title')->equal('type')->order('id asc')->page(true, true);
    }

    /**
     * 内容页面编辑
     * @auth true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function pageEdit()
    {

        $this->title =  input('type') ?? '';
        $this->__sysdata('page_form', 'javascript:history.back()');
    }

    /**
     * 显示并保存数据
     * @param string $template 模板文件
     * @param string $history 跳转处理
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function __sysdata(string $template, $history = '')
    {
        $id = $this->request->get('id');
        if ($this->request->isGet()) {
            $model = new ConfigBannerModel();
            $info = $model->where(['is_deleted' => 0,'id'=>$id])->find();
            $agreement = [
                'data' => $info
            ];
            $this->fetch($template,$agreement);
        }
        if ($this->request->isPost()) {
            if (is_string(input('data'))) {
                $data = json_decode(input('data'), true) ?: [];
            } else {
                $data = $this->request->post();
            }
            $data['create_time'] = time();
            $model = new ConfigBannerModel();
            if ($id){
                if ($model->where(['is_deleted' => 0,'id'=>$id])->update($data) !== false) {
                    $this->success('内容保存成功！', $history);
                } else {
                    $this->error('内容保存失败，请稍候再试!');
                }
            }else{
                if ($model->insert($data) !== false) {
                    $this->success('内容保存成功！', $history);
                } else {
                    $this->error('内容保存失败，请稍候再试!');
                }
            }

        }
    }


    public function del()
    {
    }

    /**
     * 删除
     * @auth true
     * @throws DbException
     */
    public function remove()
    {
        $this->_delete(ConfigBannerModel::class);
    }
}